<?php
/**
 * 文件类型
 */

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

const FILE_LX = 1;
const FILE_YS = 2;
const FILE_JS = 3;
const FILE_LOG = 4;
const FILE_JS_ACTIVITY = 5;
const FILE_JS_DESIGN = 6;
const FILE_FINANCE = 7;
const FILE_XZ = 8;
const FILE_HZD = 9;
const FILE_EMAIL = 10;
const FILE_COMMON_FORM = 11;
function ret_json($state,$msg,$data = [])
{
    exit(json_encode(['state'=>$state,'msg'=>$msg,'data'=>$data],JSON_UNESCAPED_UNICODE));
}

function ret_arr($state,$msg,$data = [])
{
    return ['state'=>$state,'msg'=>$msg,'data'=>$data];
}

if(!function_exists("success")){
    function success($msg,$data = []){
        return response()->json(['state'=>'ok','msg'=>$msg,'data'=>$data]);
    }
}

if(!function_exists("error")){
    function error($msg,$data = []){
        return response()->json(['state'=>'err','msg'=>$msg,'data'=>$data]);
    }
}

function pp($data)
{
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}

/**
 * @param $xmlobject
 * @return mixed
 * @desc xml转数组1
 */
function xml2array($xmlobject) {
    if ($xmlobject) {
        foreach ((array)$xmlobject as $k=>$v) {
            $data[$k] = !is_string($v) ? xml2array($v) : $v;
        }
        return $data;
    }
}

/**
 * @param $xml
 * @return mixed
 * @desc xml 转数组2
 */
 function xmlToArray($xml)
{
    return json_decode(json_encode(simplexml_load_string($xml)), true);
}

/**
 * @param $data
 * @param string $encoding
 * @param string $root
 * @return string
 * @desc 数组转xml
 */
function arr2xml($data, $encoding='utf-8', $root='think') {
    $xml    = '<?xml version="1.0" encoding="' . $encoding . '"?>';
    $xml   .= '<' . $root . '>';
    $xml   .= data_to_xml($data);
    $xml   .= '</' . $root . '>';
    return $xml;
}

/**
 * 数据XML编码
 * @param mixed $data 数据
 * @return string
 */
function data_to_xml($data) {
    $xml = '';
    foreach ($data as $key => $val) {
        is_numeric($key) && $key = "item id=\"$key\"";
        $xml    .=  "<$key>";
        $xml    .=  ( is_array($val) || is_object($val)) ? data_to_xml($val) : $val;
        list($key, ) = explode(' ', $key);
        $xml    .=  "</$key>";
    }
    return $xml;
}


######################################批量更新##################################################

/**

 * 批量更新函数

 * @param $data array 待更新的数据，二维数组格式

 * @param array $params array 值相同的条件，键值对应的一维数组

 * @param string $field string 值不同的条件，默认为id

 * @return bool|string

 */

function batchUpdate($table,$data, $field, $params = [])

{

   if (!is_array($data) || !$field || !is_array($params)) {

      return false;

   }



    $updates = parseUpdate($data, $field);

    $where = parseParams($params);



    // 获取所有键名为$field列的值，值两边加上单引号，保存在$fields数组中

    // array_column()函数需要PHP5.5.0+，如果小于这个版本，可以自己实现，

    // 参考地址：http://php.net/manual/zh/function.array-column.php#118831

    $fields = array_column($data, $field);

    $fields = implode(',', array_map(function($value) {

        return "'".$value."'";

    }, $fields));



    $sql = sprintf("UPDATE `%s` SET %s WHERE `%s` IN (%s) %s", $table, $updates, $field, $fields, $where);



   return $sql;

}



/**

 * 将二维数组转换成CASE WHEN THEN的批量更新条件

 * @param $data array 二维数组

 * @param $field string 列名

 * @return string sql语句

 */

function parseUpdate($data, $field)

{

    $sql = '';

    $keys = array_keys(current($data));

    foreach ($keys as $column) {



        $sql .= sprintf("`%s` = CASE `%s` \n", $column, $field);

        foreach ($data as $line) {

            $sql .= sprintf("WHEN '%s' THEN '%s' \n", $line[$field], $line[$column]);

        }

        $sql .= "END,";

    }



    return rtrim($sql, ',');

}



/**

 * 解析where条件

 * @param $params

 * @return array|string

 */

function parseParams($params)

{

   $where = [];

   foreach ($params as $key => $value) {

      $where[] = sprintf("`%s` = '%s'", $key, $value);

   }



   return $where ? ' AND ' . implode(' AND ', $where) : '';

}

######################################批量更新##################################################

//http请求封装
/**
 * @param $url
 * @param null $data
 * @param string $method
 * @param array $header
 * @param bool $https
 * @param int $timeout
 * @return bool|\Illuminate\Http\JsonResponse|string
 * @desc 自定义curl请求兼容get请求
 */
function curl($url, $data=null, $method='get', $header = array("content-type: application/json"), $https=true, $timeout = 5){
    $method = strtoupper($method);
    $ch = curl_init();//初始化
    curl_setopt($ch, CURLOPT_URL, $url);//访问的URL
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//只获取页面内容，但不输出
    if($https){
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
    }
    if ($method != "GET") {
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
        }
        if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
    $result = curl_exec($ch);//执行请求
    if($result === false) return fail_json(1,curl_error($ch));
    curl_close($ch);//关闭curl，释放资源
    return $result;
}


/******************************身份验证*******************/
//验证身份证
  function is_id_card($id_card){
    if(strlen($id_card) == 18){
        return  idcard_checksum18($id_card);
    }elseif((strlen($id_card) == 15)){
        $id_card =  idcard_15to18($id_card);
        return  idcard_checksum18($id_card);
    }else{
        return false;
    }
}
// 计算身份证校验码，根据国家标准GB 11643-1999
  function idcard_verify_number($idcard_base){
    if(strlen($idcard_base)!=17){
        return false;
    }
    //加权因子
    $factor=array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);
    //校验码对应值
    $verify_number_list=array('1','0','X','9','8','7','6','5','4','3','2');
    $checksum=0;
    for($i=0;$i<strlen($idcard_base);$i++){
        $checksum += substr($idcard_base,$i,1) * $factor[$i];
    }
    $mod=$checksum % 11;
    $verify_number=$verify_number_list[$mod];
    return $verify_number;
}
// 将15位身份证升级到18位
  function idcard_15to18($idcard){
    if(strlen($idcard)!=15){
        return false;
    }else{
        // 如果身份证顺序码是996 997 998 999，这些是为百岁以上老人的特殊编码
        if(array_search(substr($idcard,12,3),array('996','997','998','999')) !== false){
            $idcard=substr($idcard,0,6).'18'.substr($idcard,6,9);
        }else{
            $idcard=substr($idcard,0,6).'19'.substr($idcard,6,9);
        }
    }
    $idcard = $idcard . idcard_verify_number($idcard);
    return $idcard;
}
// 18位身份证校验码有效性检查
  function idcard_checksum18($idcard){
    if(strlen($idcard)!=18){
        return false;
    }
    $idcard_base=substr($idcard,0,17);
    if(idcard_verify_number($idcard_base)!=strtoupper(substr($idcard,17,1))){
        return false;
    }else{
        return true;
    }
}
/******************************身份验证*******************/

/********************************还原货币金额*************/
function parseMoney($money){
    if(\Illuminate\Support\Str::contains($money,'.')){
        $money = explode('.',$money);
        $money = $money[0] ?? 0;
    }
    $money_after = preg_replace('/,/','',$money);
    return intval($money_after);

}

function fomateMoney(string $currency='CNY',$money=0){

    try {
        $money = resetMoney($money);
        if (is_string($money)) $money = floatval($money);
        $money = number_format($money, 2);
       if($currency) return $currency . ' ' . $money;
       return $money;
    }catch (\Exception $e){
        return 'CNY' . number_format($money);
    }
}


function resetMoney($money){
    $money = preg_replace('/[A-Z]/','',$money);
    if(\Illuminate\Support\Str::contains($money,'.')){
        $money = explode('.',$money);
        $money = $money[0] ?? 0;
    }
    $money = trim(str_replace(',','',$money));
    return bcadd($money,'0.00',2);
}
/********************************还原货币金额*************/


/**************获取文件大小*******************/
function getSize($size) {
    $units = [' B', ' KB', ' MB', ' GB', ' TB'];

    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;

    return number_format($size, 2) . $units[$i];

}
/**************获取文件大小*******************/

/****************获取ip地址****************/
function get_real_ip(){
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。

    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {

        $ip = getenv('HTTP_CLIENT_IP');

    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {

        $ip = getenv('HTTP_X_FORWARDED_FOR');

    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {

        $ip = getenv('REMOTE_ADDR');

    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {

        $ip = $_SERVER['REMOTE_ADDR'];

    }

    return preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
}
/****************获取ip地址****************/


if(!function_exists('isPM')){
    function isPM()
    {
        return in_array(roleid(),\App\Http\Controllers\Constant\Constant::MANAGER_LIST);
    }


    /**
     * 附件Url截去域名
     *
     * @param string $asbUrl
     * @return string
     */
     function relativeUrl(string $asbUrl)
    {
        if (is_null($asbUrl)) return $asbUrl;
        preg_match('/^http(s)?:\/\/(.*)\//U', $asbUrl, $matches);
        if ($matches) {
            $domain = $matches[0];
            return Str::replace($domain, '', $asbUrl);
        }
        return $asbUrl;
    }

     function cdnImagePath($path)
    {
        try {
            $path = relativeUrl($path);
            $path = ltrim($path, '/');
            $cdnUrl = env('APP_URL');
            $cdnUrl = rtrim($cdnUrl, '/');
            return sprintf('%s/%s', $cdnUrl, $path);
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }
     function absPath($host)
    {
        return Str::replace(['https://','http://'],'',$host);
    }


    if(!function_exists('admin')){
        function admin($key=''){
            if(empty($token)) $token = request()->header('Authorization');
            $data =  Cache::get($token);
            if($key) return Arr::get($data,$key,'');
            return $data;
        }
    }

    if(!function_exists('admin_id')){
        function admin_id(){
            return admin('uid');
        }
    }

    if(!function_exists('roleid')){
        function roleid(){
            return admin('position_id');
        }
    }

    if(!function_exists('operation')){
        function operation($isSave):string
        {
            return $isSave  ? '保存' : (isPM() ? "提交" :"修改");
        }
    }

    if(!function_exists("cwName")){
        function cwName(int $payType)
        {
            $financeList = config("oa.finance");
            return Arr::get($financeList,sprintf("%s.name",$payType),'-');
        }
    }

    if(!function_exists("isCompanyApprover")) {
        function isCompanyApprover($role=0)
        {
            $role = $role ?: roleid();
            $approver_list = config('oa.position');
            return array_key_exists($role, $approver_list);
        }
    }
    //验证手机号
if(!function_exists("validateMobile")) {
    function validateMobile($mobile)
    {
        // 中国大陆手机号码正则：以1开头，第二位为3-9，后面9位为数字
        $pattern = '/^1[3-9]\d{9}$/';
        return preg_match($pattern, $mobile) === 1;
    }
}


}


